package br.ucb.util;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import br.ucb.bean.Professor;
import br.ucb.dao.ProfessorDAO;

@FacesConverter("ProfessorConverter")
public class ProfessorConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) throws ConverterException {
		if (value == null) {
			return null;
		}
		try {
			SimpleEntityManager manager = new SimpleEntityManager("sacop");
			manager.beginTransaction();
			Professor professor = new ProfessorDAO(manager.getEntityManager()).getById(Integer.parseInt(value));
			manager.close();
			return professor;
		} catch (Exception e) {
			e.printStackTrace();
			return new Object();
		}
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object object) throws ConverterException {
		if (object == null) {
			return null;
		}
		Professor professor = (Professor) object;
		return Integer.toString(professor.getCodigo());
	}

}
